import React, { Component } from 'react';
import { Input, Space, List, Avatar, Image } from 'antd';

import { SearchOutlined, FolderOutlined, FileOutlined, UserOutlined, SettingOutlined } from '@ant-design/icons';
import { connect } from 'umi';

import styles from './index.less';
import { request, onEmit, onListen } from '../utils/request'
import { syncTopicConstants } from '../constants/syncTopicConstants'
import { asyncTopicConstants } from '../constants/asyncTopicConstants'

@connect(({ global, listModel }) => ({ global, listModel }))

class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {

        };

    }



    componentDidMount() {
        this.initSlogan()
        this.initAvatar()
        this.initSearch()
    }


    initSearch = () => {
        this.props.dispatch({ type: 'global/initSearch' })
    }

    initSlogan = () => {
        this.props.dispatch({ type: 'global/getSlogan' })
    }

    initAvatar = () => {
        this.props.dispatch({ type: 'global/getAvatar' })
    }


    onInputChange = (e) => {
        this.setPresearchPosition(e)
        this.props.dispatch({ type: 'global/doSearchPlugin', keyword: e.target.value })
    }



    setPresearchPosition = (e) => {
        let tmpObj = document.getElementById('utilCannotDel')
        let inputObj = document.getElementById('input')
        tmpObj.innerText = e.target.value
        tmpObj.style.fontSize = document.defaultView.getComputedStyle(utilCannotDel, "").fontSize
        tmpObj.style.fontFamily = document.defaultView.getComputedStyle(utilCannotDel, "").fontFamily

        const lengthPx = tmpObj.clientWidth
        const leftPx = inputObj.offsetLeft
        const heightPx = tmpObj.clientHeight
        const topPx = inputObj.offsetTop

        const x = leftPx + lengthPx
        const y = topPx + parseInt(heightPx / 2) + 1
        this.props.dispatch({ type: "global/setPreSearchPosition", payload: { x, y } })
    }




    composeSearchRequest = (type: string, input: string | null, extInfo?: Object, subInput?: string,) => {
        return { type: type, subInput: subInput, input: input, extInfo: extInfo }
    }



    inputOnDrop = (e) => {
        e.preventDefault()
        const files = e.dataTransfer.files
        if (files && files.length > 0) {
            const path = files[0].path
            const lastName = path.split("/").pop()
            let iconType = "folder"
            if (lastName.indexOf(".") > 0) {
                iconType = "file"
            }
            const extInfo = { ...this.state.extInfo, path: path }
            this.setState({ iconType: iconType, subInput: lastName, extInfo: extInfo })
            const payload = this.composeSearchRequest(iconType, null, extInfo, lastName)
            onEmit(asyncTopicConstants.doSearchPlugin, payload)
        }
    }





    renderPrefixIcon = () => {
        const { iconType, subInput } = this.props.global
        if (iconType == "keyword") {
            return (<SearchOutlined style={{ fontSize: 24, color: '#6b6c6c' }} />)
        } else if (iconType == "folder") {
            return (<div className={styles.folderStyle} ><FolderOutlined style={{ fontSize: 18, color: '#6b6c6c' }} />{subInput}</div>)
        } else if (iconType == "file") {
            return (<div className={styles.folderStyle} ><FileOutlined style={{ fontSize: 18, color: '#6b6c6c' }} />{subInput}</div>)
        } else if (iconType == "listPlugin") {
            return (<div className={styles.listPluginStyle} >&nbsp;{subInput}&nbsp;</div>)
        } else if (iconType == "fusionPlugin") {
            return (<div className={styles.fusionPluginStyle} >&nbsp;{subInput}&nbsp;</div>)
        }
    }

    openPreference = () => {
        onEmit(asyncTopicConstants.doRunSysPluginByName, "preference")
    }

    renderSuffixIcon = () => {
        if (this.props.global.avatar == null) {
            return (<Avatar style={{ backgroundColor: '#87d068' }} icon={<UserOutlined />} onClick={this.openPreference} />)
        } else {
            return (<Avatar src={<Image src={this.props.global.avatar} style={{ width: 32 }} onClick={this.openPreference} />} />)
        }
    }

    handleKeyDown = (e) => {
        const { cursor, searchResult, relativeCursor } = this.state
        // console.info("e.keyCode", e.keyCode)
        if (e.keyCode === 38 && cursor >= 0) {
            // 向上滚动
            this.setState(prevState => {
                const theCursor = cursor == 0 ? searchResult.length - 1 : prevState.cursor - 1


                // 设置可视范围的序号
                let theRelativeCursor = relativeCursor
                if (relativeCursor > 1) {
                    theRelativeCursor = relativeCursor - 1
                }
                if (theRelativeCursor > 9) {
                    theRelativeCursor = 9
                }

                // 设置滚动
                let searchList = document.querySelector("#searchList")
                if (theRelativeCursor == 1) {
                    searchList?.scrollTo(0, theCursor * 60)
                }
                console.info("searchResult.length up", searchResult.length, theCursor, cursor, theRelativeCursor)


                return ({ cursor: theCursor, relativeCursor: theRelativeCursor })
            })
        } else if (e.keyCode === 40 && cursor <= searchResult.length - 1) {
            // 向下滚动
            this.setState(prevState => {
                const theCursor = cursor == searchResult.length - 1 ? 0 : prevState.cursor + 1
                // 设置可视范围的序号
                let theRelativeCursor = theCursor + 1
                if (theCursor > 8) {
                    theRelativeCursor = 9
                }
                // 设置滚动
                let searchList = document.querySelector("#searchList")
                if (theRelativeCursor == 9) {
                    searchList?.scrollTo(0, (theCursor - 8) * 60)
                } else if (theCursor == 0) {
                    searchList?.scrollTo(0, 0)
                }
                return ({ cursor: theCursor, relativeCursor: theRelativeCursor })
            })

        } else if (e.keyCode === 27) {
            console.info("this.state.keyword", this.state.keyword)
            if (this.state.keyword == "") {
                onEmit(asyncTopicConstants.switchHide)
            } else {
                // todo 首次按ESC清理input
            }
        }
    }




    renderPreSearch = () => {
        const { x, y } = this.props.global.preSearchPosition
        const preSearch = this.props.global.preSearch
        const keyword = this.props.global.keyword
        if (preSearch != "" && keyword != "" && preSearch != null) {
            if (preSearch.type == undefined) {
                return
            }
            let content = ""
            if (preSearch.type == "number") {
                content = "= " + String(preSearch.data) + "  （计算完成，command+C获取数据）"
            } else if (preSearch.type == "json") {
                content = " （已美化，command+C获取数据）"
            }

            return (<div style={{ position: "absolute", left: `${x + 2}px`, top: `${y}px`, color: "gray" }}>&nbsp;&nbsp;{content}</div>)
        }

    }

    render() {
        const { placeholder, iconType, slogan, preSearch, keyword } = this.props.global
        const thePlaceholder = iconType == "keyword" ? slogan : placeholder
        if (keyword == "") {
            this.props.dispatch({ type: 'global/initSearchHeigth' })
        }

        return (
            <div>

                <div id="utilCannotDel" style={{ width: "auto", visibility: "hidden", display: "inline-block", position: "fixed" }} ></div>
                <Input
                    autoComplete="false"
                    prefix={this.renderPrefixIcon()}
                    suffix={this.renderSuffixIcon()}
                    id="input"
                    autoComplete="off"
                    autoCapitalize="off"
                    autoCorrect="off"
                    placeholder={thePlaceholder}
                    onChange={this.onInputChange}
                    bordered={false}
                    size="large"
                    autoFocus="autofocus"
                    className={styles.mainInput}
                    onDrop={this.inputOnDrop}
                />
                {this.renderPreSearch()}
            </div >
        );
    }
}


export default Index;